package com.xiaoyu.lanling.feature.setting.service

import `in`.srain.cube.util.CLog
import android.app.Notification
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.os.Build
import android.os.IBinder
import androidx.annotation.RequiresApi
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.data.NotificationData
import com.xiaoyu.lanling.feature.setting.util.NotificationUtil

class NotificationService : Service() {

    companion object {
        private val TAG = NotificationService::class.java.simpleName
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (intent == null) {
            stop()
            return START_NOT_STICKY
        }
        showNotification()
        return super.onStartCommand(intent, flags, startId)
    }

    private fun showNotification() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            val intent = NotificationUtil.instance.createIntent(this) ?: return
            val notification = buildNotification(getString(R.string.notification_service_title), getString(R.string.notification_service_text), intent)
            startForeground(NotificationData.NotificationId.NOTIFICATION_SERVICE, notification)
        }
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onDestroy() {
        CLog.i(TAG, "onDestroy()")
        super.onDestroy()
        stopForeground(true)
    }

    private fun stop() {
        stopForeground(true)
        stopSelf()
    }

    @RequiresApi(Build.VERSION_CODES.N)
    private fun buildNotification(title: String, text: CharSequence?, activityIntent: Intent): Notification {
        /**
         * npe risk .@see[android.app.PendingIntent.getActivity]
         */
        val pendingIntent = PendingIntent.getActivity(this, 0, activityIntent, PendingIntent.FLAG_UPDATE_CURRENT)
        return NotificationUtil.instance.buildNotification(title, text, pendingIntent)
    }
}